const { mysql, pool, Result, Myquery } = require('../connect');
const express = require('express')
const router = express.Router()

router.get('/',(req,res)=>{
	getList(req,res);
})

router.post('/add',(req,res)=>{
	insert(req,res);
})


router.post('/del',(req,res)=>{
	del(req,res);
})

router.get('/delAll',(req,res)=>{
	delAll(req,res);
})


router.post('/update',(req,res)=>{
	update(req,res);
})

// 获取数据
function getList(req,res) {
	var sql = "SELECT * FROM `todolist`"
	console.log(sql)
	
    new Myquery(sql,(err,r)=>{
    	let code = 1,data = r,msg = '成功';

		if (err) {
			code = -1;
			msg = err;
		}
		res.json(new Result({msg:msg,data:data}))
    })	
}

// 插入数据
function insert(req,res) {
	var text = req.params.text || req.query.text || req.body.text;
	if(!text) {
		res.json(new Result({msg:'新增TODO不能为空',code:-1}))
		return;
	}
	var sql = "INSERT INTO `todolist` (`text`) VALUES ( ? )"
	var inserts = [text]
	sql = mysql.format(sql, inserts)
	console.log(sql)
	
    new Myquery(sql,(err,r)=>{
    	let code = 1,data = r,msg = '成功';

		if (err) {
			code = -1;
			msg = err;
		}
		res.json(new Result({msg:msg,data:data}))
    })	
}


// 删除数据
function del(req,res) {
	var id = req.params.id || req.query.id || req.body.id;
	var sql = "DELETE from `todolist` WHERE id = ?"
	var inserts = [id]
	sql = mysql.format(sql, inserts)
	console.log(sql)
	
    new Myquery(sql,(err,r)=>{
    	let code = 1,data = r,msg = '成功';

		if (err) {
			code = -1;
			msg = err;
		}
		res.json(new Result({msg:msg,data:data}))
    })	
}

// 删除所有数据
function delAll(req,res) {
	var sql = "DELETE from `todolist`"
	console.log(sql)
	
    new Myquery(sql,(err,r)=>{
    	let code = 1,data = r,msg = '成功';

		if (err) {
			code = -1;
			msg = err;
		}
		res.json(new Result({msg:msg,data:data}))
    })	
}

// 修改数据
function update(req,res) {
	var id = req.body.id;
	var sql = "UPDATE `todolist` set completed=abs(completed-1) where id=?;"
	var inserts = [id]
	sql = mysql.format(sql, inserts)
	console.log(sql)
	
    new Myquery(sql,(err,r)=>{
    	let code = 1,data = r,msg = '成功';

		if (err) {
			code = -1;
			msg = err;
		}
		res.json(new Result({msg:msg,data:data}))
    })	
}
module.exports = router;